import json
from django.http import HttpResponse
from bazy.login import Login
from bazy.models import OffenseType
from bazy.forms import CreateOffenseTypeForm


def create(request):
	log = Login(request)
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	form = CreateOffenseTypeForm(request.POST)
	if form.is_valid() is False:
		return HttpResponse(json.dumps([{'Error':-2}]))
	model = OffenseType(name=request.POST.get('name',''),harmfulness=request.POST.get('harmfulness',0),overview=request.POST.get('overview',0))
	model.save()
	return HttpResponse(json.dumps([{'Error':0}]))

def getAll(request):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method!='POST':
		return HttpResponse(json.dumps([{'Error':-2}]))
	offenseTypeArray = OffenseType.objects.all();
	jsonList = list()
	for offenseType in offenseTypeArray:
		jsonList.append({'id':offenseType.id,
						 'name':offenseType.name,
						 'harmfulness':offenseType.harmfulness,
						 'overview':offenseType.overview, })
	return HttpResponse(json.dumps(jsonList))

def get(request):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method!='POST':
		return HttpResponse(json.dumps([{'Error':-2}]))
	id= request.POST.get('id',-1)
	offenseType = OffenseType.objects.get(pk=id)
	return HttpResponse(json.dumps({'id':offenseType.id,
						 'name':offenseType.name,
						 'harmfulness':offenseType.harmfulness,
						 'overview':offenseType.overview, }))

def edit(request):
	log = Login(request);
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	if request.method!='POST':
		return HttpResponse(json.dumps([{'Error':-2}]))
	id= request.POST.get('id',0)
	if id==0:
		return HttpResponse(json.dumps([{'Error':-1}]))
	offenseType = OffenseType.objects.get(pk=id)
	offenseType.name=request.POST.get('name',0)
	offenseType.harmfulness=request.POST.get('harmfulness',0)
	offenseType.overview=request.POST.get('overview',0)
	offenseType.save()
	return HttpResponse(json.dumps([{'Error':0}]))

def delete(request):
	log = Login(request)
	if log.isLogged() is not True:
		return HttpResponse(json.dumps([{'Error':-1}]))
	id= request.POST.get('id',0);
	try:
		offense = OffenseType.objects.get(pk=id)
	except OffenseType.DoesNotExist:
		return HttpResponse(json.dumps([{'Error':-3}]))
	offense.delete()
	return HttpResponse(json.dumps([{'Error':0}]))